package org.yystory.ui;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.yystory.dataobject.FavouriteObject;
import org.yystory.entity.Favourite;
import org.yystory.service.StoryService;
import org.yystory.utility.ErrorParser;

import com.alibaba.fastjson.JSON;

public class FavouriteListServlet extends HttpServlet {

	private static final long serialVersionUID = 4094486965027267707L;

	public FavouriteListServlet() {
		super();
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		response(request, response);
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		response(request, response);
	}

	private void response(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		try {
			int userId = Integer.parseInt(request.getParameter("uid"));
			Favourite[] favourites = StoryService.favouriteList(userId);
			List<FavouriteObject> list = new ArrayList<FavouriteObject>();
			for (Favourite favourite : favourites) {
				FavouriteObject object = new FavouriteObject();
				object.setId(favourite.getId());
				object.setLastSequenceId(favourite.getSequence().getId());
				object.setStoryId(favourite.getStory().getId());
				object.setStoryName(favourite.getStory().getName());
				list.add(object);
			}
			response.getWriter().print(JSON.toJSONString(list));
			response.getWriter().close();
		} catch (Exception e) {
			response.getWriter().print(
					ErrorParser.parseError("FavouriteListServlet", e.getClass()
							.getName() + ":" + e.getMessage()));
			response.getWriter().close();
		}
	}

}
